package com.design.pool;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Vector;

/**
 * 数据库连接池
 */
public class ConnectionPool {

    private Vector<Connection> pool;

    private int poolSize = 100;

    private String url = "jdbc:mysql://192.168.110.105:3306/external_service";

    private String user = "root";

    private String password = "huayue@123";

    private String driverClassName = "com.mysql.jdbc.Driver";

    public ConnectionPool() {
        pool = new Vector<>(poolSize);
        try {
            Class.forName(driverClassName);
            for (int i = 0; i < poolSize; i++) {
                Connection connection = DriverManager.getConnection(url, user, password);
                pool.add(connection);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public synchronized Connection getConnection() {
        if (pool.size() > 0) {
            System.out.println("size:"+pool.size());
            Connection conn = pool.get(0);
            pool.remove(conn);
            return conn;
        }
        return null;
    }

    public synchronized void release(Connection conn) {
        System.out.println("before:"+pool.size());
        pool.add(conn);
        System.out.println("after:"+pool.size());
    }
}
